<template>
  <div class="goods">
    <div class="top_bar">
      <van-nav-bar
        left-text="返回"
        right-text="收藏"
        left-arrow
        @click-right="shoucang"
      >
        <template #left>
          <van-icon
            name="arrow-left"
            size="20"
            @click="$router.back()"
            style="margin-right: 10px"
          />
          <van-icon name="wap-home-o" size="20" @click="goToIndex" />
        </template>
      </van-nav-bar>
    </div>
    <div class="goods_info">
      <van-image width="100%" height="100%" :src="data.goods_big_logo" />
      <p class="price">
        <span>{{ data.goods_price }}</span>
      </p>
      <h1>{{ data.goods_name }}</h1>
    </div>
    <div class="goods_relevant">
      <h4 class="goods_relevant_title">今日推荐</h4>
      <van-row gutter="">
        <van-col span="8" v-for="item in goodslist" :key="item.goods_id">
          <van-image
            width="100"
            height="100"
            :src="item.goods_big_logo"
            @click="goto('/goods/' + item.goods_id)"
          />
          <h5>{{ item.goods_name }}</h5>
        </van-col>
      </van-row>
    </div>
    <div class="goods_more_info">
      <h4 class="goods_introduce_title">商品介绍</h4>
      <div class="goods_introduce" v-html="data.goods_introduce"></div>
    </div>
    <div @click="toTop" v-show="backtToTopIsShow" class="toTop">
      <i class="iconfont icon-icon-test"></i>
    </div>
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon
        icon="cart-o"
        text="购物车"
        :badge="cartlist.length == 0 ? '' : cartlist.length"
        @click="goto('/cart')"
      />
      <van-goods-action-icon icon="shop-o" text="店铺" />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="onAddbtn"
      />
      <van-goods-action-button
        type="danger"
        text="立即购买"
        @click="onBuybtn"
      />
    </van-goods-action>
    <van-sku
      class="sku"
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :quota="quota"
      :quota-used="quotaUsed"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="addGoodsToCart"
      @stepper-change="stepperChange"
      :show-add-cart-btn="isShowAdd"
      :stepper-title="stepperTitle"
    >
      <template #sku-stepper>
        <van-stepper v-model="value" @change="stepperChange" />
      </template>
    </van-sku>
  </div>
</template>
<script>
export default {
  name: "Goods",
  data() {
    return {
      //数量选择组件左侧文案
      stepperTitle: "",
      // 是否显示加入购物车按钮
      isShowAdd: true,
      // 相关商品
      goodslist: [],
      // 当前商品详情
      data: {},
      //加入购物车sku收起与显示
      show: false,
      // 立即购买sku收起与显示
      show1: false,
      //当前商品id
      goodsId: "",
      //商品限购数
      quota: 0,
      //已经购买过的数量
      quotaUsed: 1,
      //商品 sku 数据
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: "", // skuKeyName：规格类目名称
            k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: "1",
                name: "默认",
                imgUrl: "",
                previewImgUrl: "",
              },
            ],
            largeImageMode: true, //  是否展示大图模式
          },
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 100, // 价格（单位分）
            stock_num: 110, // 当前 sku 组合对应的库存
          },
        ],
        price: 0, // 默认价格（单位元）
        stock_num: 0, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        hide_stock: false, // 是否隐藏剩余库存
      },
      //商品信息
      goods: {
        // 默认商品 sku 缩略图
        picture: "https://img01.yzcdn.cn/1.jpg",
      },
      // 步进器数量
      value: 1,
      //返回顶部显示与否
      backtToTopIsShow: false,
    };
  },
  mounted() {
    // 隐藏底部bar
    this.$parent.isShowbar = false;
  },
  created() {
    // 获取地址携带商品id
    const { id } = this.$route.params;
    // 获取当前商品
    this.getData(id);
    // 添加滚动事件监听
    window.addEventListener("scroll", this.backtToTop, true);
  },

  destroyed() {
    // 销毁该组件时显示底部bar
    this.$parent.isShowbar = true;
  },
  // 路由发生更新
  beforeRouteUpdate(to, from, next) {
    if (to.params.id != from.params.id) {
      scrollTo({ top: 0 });
      this.getData(to.params.id);
    }
    next();
  },
  methods: {
    // 回到顶部判断
    backtToTop(e) {
      if (scrollY >= 1000) {
        this.backtToTopIsShow = true;
      } else {
        this.backtToTopIsShow = false;
      }
    },
    //回到顶部
    toTop() {
      window.scrollTo({ top: 0, behavior: "smooth" });
    },
    //购买按钮控制sku显示与隐藏
    onBuybtn() {
      this.show = true;
      this.isShowAdd = false;
      this.stepperTitle = "购买数量";
    },
    //加入购物车按钮控制sku显示与隐藏
    onAddbtn() {
      this.show = true;
      this.isShowAdd = true;
      this.stepperTitle = "加入数量";
    },
    //返回首页
    goToIndex() {
      this.$router.push("/index");
    },
    // 获取当前商品商品信息请求
    getData(id) {
      this.$request.post("/goods/" + id).then(({ data }) => {
        this.getGoodslist(data.data.cat_one_id);
        if (data.status == 200) {
          this.data = data.data;
          this.goodsId = data.data.goods_id;
          // sku图片显示
          this.goods.picture = data.data.goods_big_logo;
          // 商品总库存
          this.sku.stock_num = this.sku.list[0].stock_num =
            data.data.goods_number;
          // 颜色选择
          this.sku.tree[0].v[0].imgUrl = this.sku.tree[0].v[0].imgUrl =
            data.data.goods_big_logo;
          // 价格
          this.sku.price = data.data.goods_price;
          this.sku.list[0].price = data.data.goods_price * 100;
        }
      });
    },
    // 获取相关类型商品
    getGoodslist(cat) {
      this.$request
        .post("/relevant", {
          goodsType: cat,
          limit: 12,
        })
        .then(({ data }) => {
          this.goodslist = data.data;
        });
    },
    // 收藏商品
    shoucang() {
      
    },
    // 添加商品至购物车
    async addGoodsToCart() {
      // 判断用户是否登录与有效性
      const data = await this.$store.dispatch("tokenCheck");
      if (data.status != 200) {
        this.goto("/login");
        return;
      }
      this.$request
        .post(
          "/addToCart",
          {
            username: this.userInfo.username,
            id: this.data.goods_id,
            num: this.value,
          },
          {
            headers: {
              token: this.userInfo.token,
            },
          }
        )
        .then(({ data }) => {
          if (data.status != 200 && data.status != 201) return;
          //添加成功后修改本地数据
          if (data.status == 200) {
            this.$store.commit("cart/addGoodToCart", this.data);
            this.$store.commit("cart/changeQty", {
              goods_id: this.data.goods_id,
              Cartcount: this.value,
            });
          }
          if (data.status == 201) {
            this.$store.commit("cart/changeQty", {
              goods_id: this.data.goods_id,
              Cartcount:
                this.value +
                this.cartlist.filter(
                  (item) => item.goods_id === this.data.goods_id
                )[0].Cartcount,
            });
          }
          this.show = false;
          this.$toast.success("加入购物车成功");
        });
    },
    //步进器变换函数
    stepperChange(value) {
      // 所选商品总价
      this.sku.list[0].price = this.data.goods_price * value * 100;
    },
    // 立即购买
    async onBuyClicked() {
      // 判断用户是否登录与有效性
      const data = await this.$store.dispatch("tokenCheck");
      if (data.status != 200) {
        this.goto("/login");
        return;
      }
      this.$router.push({
        name: "SubOrder",
        query: {
          goodId: this.data.goods_id,
          num: this.value,
        },
      });
    },
    // 页面跳转
    goto(url) {
      if (this.$route.fullPath == url) {
        scrollTo({ top: 0 });
        return;
      }
      this.$router.push(url);
    },
  },
  computed: {
    // 本地购物车信息
    cartlist() {
      return this.$store.state.cart.cartlist;
    },
    // 本地用户信息
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
};
</script>
<style scoped lang="scss">
.goods {
  padding-bottom: 50px;
  .top_bar {
    position: fixed;
    top: 0;
    z-index: 100;
    width: 100%;
  }
  .goods_introduce_title,
  .goods_relevant_title {
    font-size: 20px;
  }
  .goods_info {
    padding-top: 50px;
    h1 {
      font-size: 16px;
      padding: 0 15px;
    }
    .price {
      text-align: left;
      padding: 0 0 0 15px;
      margin: 5px 0;
      span {
        font-size: 25px;
        &::before {
          font-size: 14px;
        }
      }
    }
  }
  .goods_relevant {
    padding: 0 10px;
    h5 {
      font-weight: normal;
      font-size: 12px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      text-overflow: ellipsis;
      margin: 3px;
    }
  }
  .toTop {
    position: fixed;
    right: 20px;
    bottom: 80px;
    z-index: 9999;
    .iconfont {
      font-size: 50px;
      color: red;
    }
  }
}
</style>